# Copyright (c) 2021 Presto Labs Pte. Ltd.
# Author: daniel

import requests
from coin2.exchange.product_info import ProductInfoDefault
from coin2.exchange.symbology import SymbologyInfo
from decimal import Decimal


def get_price_ticksize(filters):
  ret = []
  for ele in filters:
    ret.append([float(ele['minPrice']), float(ele['maxPrice']), float(ele['tickSize'])])
  return ret


def get_price_ticksize_v2(symbol, filters):
  ret = []
  if symbol in ['BTC-TRY', 'ETH-TRY', 'MKR-TRY']:
    ele = filters[0]
    ret.append([float(ele['minPrice']), float(ele['maxPrice']), float(1.0)])
    return ret

  for ele in filters:
    ret.append([float(ele['minPrice']), float(ele['maxPrice']), float(ele['tickSize'])])
  return ret


def generate():
  mea = 'Spot.Btcturk.v1'
  me = 'Spot.Btcturk'
  default = ProductInfoDefault()
  symbol_info = SymbologyInfo()
  data = requests.get("https://api.btcturk.com/api/v2/server/exchangeinfo").json()['data']

  pis = []
  for info in data['symbols']:
    if info["status"] != "TRADING":
      continue

    native_symbol = info['nameNormalized']
    native_base = info['numerator']
    native_quote = info['denominator']
    base = symbol_info.native_to_norm_currency(mea, native_base)
    quote = symbol_info.native_to_norm_currency(mea, native_quote)
    symbol = "%s-%s" % (base, quote)

    pi = dict(
        symbol=symbol,
        base=base,
        quote=quote,
        native_symbol=native_symbol,
        native_base=native_base,
        native_quote=native_quote,
        price_ticksize=get_price_ticksize_v2(symbol, info['filters']),
        qty_ticksize= float(Decimal("0.1") ** Decimal(info['numeratorScale'])),
    )

    pi = {**pi, **default.product_info(me, symbol)}
    pis.append(pi)

  pis = sorted(pis, key=lambda x: x['symbol'])
  return pis


def gen_coin1_constants():
  data = generate()
  data = convert_coin1_constants(data)
  return data


def convert_coin1_constants(data):
  symbol_list = [info['native_symbol'] for info in data]
  quote_currency_list = list({info['native_quote'] for info in data})
  base_currency_list = list({info['native_base'] for info in data})
  currency_list = base_currency_list + quote_currency_list
  return {
      'symbol_list': symbol_list,
      'currency_list': currency_list,
      'quote_currency_list': quote_currency_list,
  }


if __name__ == "__main__":
  import json
  print(json.dumps(generate(), indent=2))
